package team.seekers.table.controller;


import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import team.seekers.table.entity.vo.Classtable;
import team.seekers.table.entity.temp.CourseTable;
import team.seekers.table.entity.vo.UpdateVo;
import team.seekers.table.entity.vo.User;
import team.seekers.table.result.Result;
import team.seekers.table.service.CourseInfoService;
import team.seekers.table.service.SysuserService;
import team.seekers.table.spider.CoursesSpider;
import team.seekers.table.utils.RedisUtil;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cbj
 * @since 2021-04-26
 */
@RestController
@RequestMapping("/table/courseinfo")
public class CourseInfoController {
    @Autowired
    private CoursesSpider coursesSpider;
    @Autowired
    private CourseInfoService courseService;
    @Autowired
    private SysuserService userService;
    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("getClassTableFirstTime/{userId}")
    public Result getFirstTime(@PathVariable("userId") String userId){
        User user = userService.getUser(userId);
        List<CourseTable> courseTables = coursesSpider.getCourseTable(user, false);
        Map[][] map = courseService.saveCourseInfo(courseTables,userId);
        return Result.success().data("classTable",map);
    }
    @GetMapping("getClassTable/{userId}")
    public Result getClassTable(@PathVariable("userId")String userId){
        String result = (String) redisUtil.get(userId);
        Map[][] map;
        if(result == null){
            map = courseService.getByOpenId(userId);
            if(map!=null){
                result = JSON.toJSONString(map);
                redisUtil.set(userId,result);
            }
        }
        map = JSON.parseObject(result, Map[][].class);
        return Result.success().data("classTable",map);
    }
    @PutMapping ("/update")
    public Result updateCourse(@RequestBody UpdateVo vo){
        String userId = vo.getUserId();
        // 先更新数据库，再删除缓存
        Map[][] map = courseService.getByOpenId(userId);
        courseService.updateCourse(vo,map);
        // 删除缓存
        redisUtil.del(vo.getUserId());
        return Result.success();
    }
    @DeleteMapping("/delete")
    public Result deleteCourse(@RequestBody UpdateVo vo){
        Map[][] map = courseService.getByOpenId(vo.getUserId());
        courseService.deleteCourse(vo,map);
        // 删缓存
        redisUtil.del(vo.getUserId());
        return Result.success();
    }
}

